<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head  >
	<title>航线管理</title>
	<#include "/commonheader.html" />
</head>
<body class="gray-bg layer-blue">
<div class="wrapper wrapper-content animated fadeInRight full-container full-height">
    <div class="row" id="same-height-row">
        <div class="col-md-12 col-sm-12 same-height-box">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <div class="btn-group table-tool" id="table-task-toolbar" role="group">
                        <button type="button" class="btn btn-outline btn-success btn-add" data-toggle="tooltip"
                                title="添加" id="btn-add">
                            <i class="fa fa-plus" aria-hidden="true"></i>
                        </button>
                        <button type="button" class="btn btn-outline btn-success btn-refresh" data-toggle="tooltip"
                                title="刷新" id="btn_refresh">
                            <i class="fa fa-refresh" aria-hidden="true"></i>
                        </button>
                    </div>
                    <div class="btn-group table-tool pull-right" id="table2-toolbar" role="group">
                        <button type="button" class="btn btn-outline btn-success btn-refresh" data-toggle="tooltip"
                                title="查询" id="btn-auto">
                            自动组连线
                        </button>
                    </div>
                    <table id="table-task" data-classes="table table-hover table-condensed">
                        <thead>
                        <tr>
                            <!--<th data-field="id" data-formatter="orderFormatter">序号</th>-->
                            <th data-checkbox="true"></th>
                            <th data-field="loopName" data-formatter="nameFormatter">任务环</th>
                            <th data-field="startDate">有效期起</th>
                            <th data-field="endDate">有效期止</th>
                            <th data-field="status" data-formatter="statusFormatter">当前状态</th>
                            <th data-field="badRoute" data-formatter="routeStatusFormatter">差航线</th>
                            <th data-field="updateTime">最后修改</th>
                            <th data-field="operation" data-formatter="operateFormatter" data-events="operateEvents">
                                操作
                            </th>
                        </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>

    </div>
</div>
<div class="wrapper wrapper-content layer-body" id="layerBody" style="display:none;">
    <div class="btn-group table-tool" role="group">
        <label class="pull-left" style="line-height:28px;margin-bottom:0;">&nbsp;&nbsp;有效期<font style="color:red;">*</font>：</label>

        <input type="text" placeholder="开始日期" style="width:90px;"
               class="table-tool-btn pull-left text-center" id="startDate"/>
        <input type="text" placeholder="结束日期" style="width:90px; border-right: 1px solid #1c84c6;"
               class="table-tool-btn pull-left text-center" id="endDate"/>
        <label class="pull-left" style="line-height:28px;margin-bottom:0;margin-left:5px;"> 机组标准<font
                style="color:red;">*</font>：</label>
        <select name="crewNumberType" id="crewNumberType" style="border-right: 1px solid #1c84c6;"></select>
        <label class="pull-left" style="line-height:28px;margin-bottom:0;margin-left:5px;"> 性质<font
                style="color:red;">*</font>：</label>
        <select name="badRoute" id="isBadRoute">
            <option value="0">正常航线</option>
            <option value="1">差航线</option>
        </select>
        <label class="pull-left" style="line-height:28px;margin-bottom:0;margin-left:5px;"> 始飞班期<font
                style="color:red;">*</font>：</label>
        <input type="text" placeholder="班期" style="width:70px; border-right: 1px solid #1c84c6;"
               class="table-tool-btn pull-left" id="weekFristDay" maxlength="7"/>
    </div>
    <div class="table-tool pull-right" role="group">
        <button type="button" class="btn btn-outline btn-success btn-add" data-toggle="tooltip"
                title="添加" onclick="addOneDay()">添加一天
        </button>
        <button type="button" class="btn btn-outline btn-warning btn-add" data-toggle="tooltip"
                title="添加" onclick="syncFData()"  th:if=" ${dutyCode} eq 'C'">同步飞行
        </button>
    </div>
    <div class="btn-group table-tool" role="group" style="margin-top:5px;">
        <label class="pull-left" style="line-height:28px;margin-bottom:0;">最少男性：</label>
        <input type="text" placeholder="数量" style="width:70px; border-right: 1px solid #1c84c6;"
               class="table-tool-btn pull-left" id="minMale"
               onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
        />
        <label class="pull-left" style="line-height:28px;margin-bottom:0;margin-left:5px;">国际航线时差6：</label>
        <input type="checkbox"
               class="table-tool-btn pull-left" id="internationalTimeZoneMore6" maxlength="7" style="margin-top:2px;"/>
    </div>

    <div id="handTable">
    </div>
</div>
<div class="wrapper wrapper-content layer-body" id="layerLinkLineBody" style="display:none;">
    <form class="form-horizontal">
        <div class="row person-item">
            <div class="col-sm-10 col-sm-offset-1">
                <div class="form-group">
                    <div class="col-xs-4 form-label-v">
                        <label>开始时间:</label>
                    </div>
                    <div class="text-left col-sm-8">
                        <input class="form-control" type="text" id="startLinkLineDate"/>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-xs-4 form-label-v">
                        <label>结束时间:</label>
                    </div>
                    <div class="text-left col-sm-8">
                        <input class="form-control" type="text" id="endLinkLineDate"/>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<div class="wrapper wrapper-content layer-body" id="layerLinkLineDataF" style="display:none;">
    <table id="table-linkLineF" data-classes="table table-hover table-condensed">
        <thead>
        <tr>
            <th data-radio="true"></th>
            <th data-field="loopName" data-formatter="nameFormatter">任务环</th>
            <th data-field="status" data-formatter="statusFormatter">当前状态</th>
            <th data-field="badRoute" data-formatter="routeStatusFormatter">差航线</th>
        </tr>
        </thead>
    </table>
</div>
<script th:inline="javascript">
    var url = '/crew/';
    var dutyCode = [[]];//页面是否只能查看
    var airportData = [];
    $(document).ready(function () {
        $.fn.select2.defaults.set("theme", "bootstrap"); //使用select2-bootstrap主题
        $("#table-task").bootstrapTable({
            /*数据参数清单*/
            //分页参数
            url: url + 'pilotTaskLoop/listTaskLoop?dutyCode=' + dutyCode,
            pagination: true,//是否分页
            pageList: [10, 25, 50, 100],
            pageSize: 25,
            pageNumber: 1,
            clickToSelect: true,
            singleSelect: false,
            showRefresh: false,                  //是否显示刷新按钮
            uniqueId: 'id',
            striped: true,//行间隔色
            locale: "${language}",
            onClickRow: function (row, $element) {
                $element.addClass('info').siblings().removeClass('info').end();
            }
        });
        $("#startLinkLineDate").datetimepicker({
            minView: "month",
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayBtn: true,
            todayHighlight: true,
            pickerPosition: "bottom-right"
        }).on("changeDate", function () {
            $('#endLinkLineDate').datetimepicker('setStartDate', $("#startLinkLineDate").val());
        });
        $("#endLinkLineDate").datetimepicker({
            minView: "month",
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayBtn: true,
            todayHighlight: true,
            pickerPosition: "bottom-right"
        }).on("changeDate", function () {
            $('#startLinkLineDate').datetimepicker('setEndDate', $("#endLinkLineDate").val());
        });
        //添加
        $("#btn-add").click(function () {
            layer.open({
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                area: ['900px', '80%'],
                btn: ["保存", "取消"],
                zIndex: 999,
                title: "添加任务",
                content: $("#layerBody"),
                yes: function (index, layero) {
                    var startDate = $("#startDate").val();
                    if (!startDate) {
                        toastr.warning("请选择开始日期！");
                        return;
                    }
                    var endDate = $("#endDate").val();
                    if (!endDate) {
                        toastr.warning("请选择结束日期！");
                        return;
                    }
                    var crewNumberType = $("#crewNumberType").val();
                    if (!crewNumberType) {
                        toastr.warning("请选择机组标准！");
                        return;
                    }
                    var weekFristDay = $("#weekFristDay").val();
                    if (!weekFristDay) {
                        toastr.warning("请输入始飞班期！");
                        return;
                    }
                    var params = {};
                    params.startDate = startDate;
                    params.endDate = endDate;
                    params.crewNumberType = crewNumberType;
                    params.weekFristDay = weekFristDay;
                    params.badRoute = $("#isBadRoute").val() == 0 ? false : true;
                    var legNum = $(".item").length;
                    if (legNum == 0) {
                        if (!$("#toast-container")[0]) {
                            toastr.warning("尚未添加任务！");
                        }
                        return;
                    } else {
                        var sum = 0;
                        $("#handTable .item .table").each(function () {
                            sum += $(this).bootstrapTable("getData").length;
                        });
                        if (sum == 0) {
                            if (!$("#toast-container")[0]) {
                                toastr.warning("尚未添加航段！");
                            }
                            return;
                        }
                    }

                    //最少男性 以及 国际航线时差6
                    params.minMale = $("#minMale").val();
                    params.internationalTimeZoneMore6 = $('#internationalTimeZoneMore6').is(":checked");
                    params.dutyCode = dutyCode;
                    params.dayList = [];
                    var isPassValid = true;
                    $("#handTable .item").each(function () {
                        var tempDayList = {};
                        tempDayList.loopDay = $(this).find(".loopDay").text();
                        var tempData = $(this).find("table").bootstrapTable("getData");
                        var isNotNull = true;
                        for (var i = 0; i < tempData.length; i++) {
                            if (!tempData[i].flightNo) {
                                toastr.warning("请输入航段的航班号");
                                isNotNull = false;
                                break;
                            }
                            if (tempData[i]._isNew) {
                                tempData[i].id = "";
                            }
                        }
                        if (isNotNull) {
                            tempDayList.flightList = tempData;
                            params.dayList.push(tempDayList);
                        } else {
                            isPassValid = false;
                        }
                    });
                    if (isPassValid) {
                        $.ajax({
                            url: url + "pilotTaskLoop/save",
                            dataType: 'json',
                            async: false,
                            type: 'post',
                            data: {data: JSON.stringify(params)},
                            success: function (data) {
                                console.log(data);
                                if (!data.errorCode && (data.success == true || data.success == "true")) {
                                    toastr.success(data.message);
                                    layer.close(index);
                                    $("#table-task").bootstrapTable("refresh");
                                }else{
                                    if (!$("#toast-container")[0]) {
                                        toastr.warning(data.message);
                                    }
                                }
                            },
                            error: function (data) {
                                if (!$("#toast-container")[0]) {
                                    toastr.warning("出错了！");
                                }
                            }
                        });
                    }
                },
                end: function (index, layero) {
                    $("#handTable").html("");
                    $("#startDate,#endDate").val(null).trigger('change');
                },
                success: function (layero, index) {
                    $("#startDate").val("").trigger("change");
                    $("#endDate").val("").trigger("change");
                    $("#crewNumberType").val("").trigger('change');
                    $("#weekFristDay").val("");
                }
            });
        });

        //刷新
        $("#btn_refresh").click(function () {
            $("#table-task").bootstrapTable('refresh');
        });
        /*自动组连线*/
        $("#btn-auto").click(function () {
            var selectData = $("#table-task").bootstrapTable("getSelections");
            if (selectData.length == 0) {
                if (!$("#toast-container")[0]) {
                    toastr.warning("请选择任务环！");
                }
                return false;
            }
            var taskIds = '';
            for (var i = 0; i < selectData.length; i++) {
                taskIds += selectData[i].id + ",";
            }
            taskIds = taskIds.substring(0, taskIds.length - 1);
            layer.open({
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                area: ['350px', '220px'],
                btn: ["保存", "取消"],
                zIndex: 999,
                title: "自动组连线",
                content: $("#layerLinkLineBody"),
                yes: function (indexLayer, layero) {
                    var loadingIndex = layer.load();
                    $.ajax({
                        type: "post",
                        url: "/pilotTaskLoop/autoCreateLinkLine",
                        data: {
                            flightDateStart: $("#startLinkLineDate").val(),
                            flightDateEnd: $("#endLinkLineDate").val(),
                            taskLoopId: taskIds,
                            dutyCode:dutyCode
                        },
                        dataType: 'json',
                        success: function (data) {
                            //事件设置可以拖动的起止时间
                            if (!data.errorCode && (data.success == true || data.success == 'true')) {
                                layer.close(indexLayer);
                                toastr.success('自动组连线成功！');
                                layer.close(loadingIndex);
                                //刷新日历及已组航班和未组航班数据
                                $("#table-task").bootstrapTable("refresh");
                            } else {
                                layer.close(loadingIndex);
                                toastr.error(data.message);
                            }
                        },
                        error: function () {
                            layer.close(loadingIndex);
                        }
                    });
                },
                cancel: function (indexLayer, layero) {
                },
                success: function (indexLayer, index) {
                    $("#startLinkLineDate").val(null).trigger("change");
                    $("#endLinkLineDate").val(null).trigger("change");
                }
            });

        });
        $("#startDate,#endDate").datetimepicker({
            minView: "month",
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayBtn: true,
            bootcssVer: 3,
            todayHighlight: true,
            pickerPosition: "bottom-right"
        });
        $("#startDate").on("change", function () {
            $("#endDate").datetimepicker("setStartDate", $("#startDate").val());
        });
        $("#endDate").on("change", function () {
            $("#startDate").datetimepicker("setEndDate", $("#endDate").val());
        });
        //几人制 样式修改
        $("#crewNumberType").select2({
            minimumResultsForSearch: Infinity,
            data: getAjaxData(url + "pilotTaskLoop/getCrewNumberType?dutyCode=" + dutyCode),
            width: "110px",
            placeholder: '请选择',
            allowClear: true,
        });
        $("#isBadRoute").select2({
            width: 80,
            minimumResultsForSearch: Infinity,
        });
        $(".table-tool .select2-container--bootstrap .select2-selection--single").css("border-right", "1px solid #2c84c6");

        $("#weekFristDay").keyup(function () {
            var reg = /^[1-7]+$/;
            if (reg.test($(this).val())) {
                return $(this).val();
            } else {
                $(this).val("");
            }
        });
        airportData = getAjaxData(url + 'select2/getAirport');
    });

    function addOneDay(data) {
        var startDate = $("#startDate").val();
        if (!startDate) {
            toastr.warning("请选择开始日期！");
            return;
        }
        var endDate = $("#endDate").val();
        if (!endDate) {
            toastr.warning("请选择结束日期！");
            return;
        }
        var len = $("#handTable .item").length;
        var flightList = [];
        var dayId = null;
        if (data) {
            flightList = data.flightList;
            dayId = data.id;
        }
        var html = constructDayHTML((len + 1), dayId);
        $("#handTable").append(html);
        updateDayText();
        $("#dayTable-" + (len + 1)).bootstrapTable({
            data: flightList,
            clickToSelect: true,
            singleSelect: true,
            showRefresh: false,                  //是否显示刷新按钮
            striped: true,//行间隔色
            locale: "${language}",
            uniqueId: 'id',
            onClickRow: function (row, $element) {
                $element.addClass('info').siblings().removeClass('info').end();
            },
            columns: [
                {
                    field: 'id',
                    title: '序号',
                    formatter: orderFormatter
                },
                {
                    field: 'loopDay',
                    title: '排序',
                    visible: false,
                },
                {
                    field: 'flightNoSelect',
                    title: '航班号',
                    editable: {
                        type: 'select2',
                        emptytext: "请选择",
                        placeholder: "请选择",
                        mode: "inline",
                        source: getSource(),
                        select2: {
                            allowClear: true,
                            templateResult: formatState,
                            containerCssClass: '',
                            templateSelection: formatSelectionState
                        },
                        validate: function (value) {
                            if ($.trim(value) == '') {
                                return '起飞机场不能为空!';
                            }
                        },
                        onblur: 'ignore'
                    }
                }, {
                    field: 'flightNo',
                    title: '航班号',
                }, {
                    field: 'departureAirport',
                    title: '起飞机场',
                    visible:false
                },{
                    field: 'departureAirport',
                    title: '起飞机场',
                    formatter: function (value, row, index) {
                        return row.departureAirportName
                    }
                    /*editable: {
                        type: 'select2',
                        emptytext: "请选择",
                        placeholder: "请选择",
                        mode: "inline",
                        source:flightSelectData,
                        select2: {
                            allowClear: true,
                            matcher: matchCustom,
                        },
                        validate: function (value) {
                            if ($.trim(value) == '') {
                                return '起飞机场不能为空!';
                            }
                        },
                        onblur:'ignore'
                    }*/
                },{
                    field: 'arrivalAirport',
                    title: '落地机场',
                    visible:false
                },
                {
                    field: 'arrivalAirportName',
                    title: '落地机场',
                    formatter: function (value, row, index) {
                        return row.arrivalAirportName
                    }
                    /* editable: {
                         type: 'select2',
                         emptytext: "请选择",
                         placeholder: "请选择",
                         mode: "inline",
                         source:airportData,
                         select2: {
                             allowClear: true,
                             matcher: matchCustom,
                         },
                         onblur:'ignore',
                         validate: function (value) {
                             if ($.trim(value) == '') {
                                 return '落地机场不能为空!';
                             }
                         },
                     }*/
                }, {
                    field: 'weeks',
                    title: '班期',
                    editable: false
                    /* editable: {
                         type: 'text',
                         emptytext: "请输入",
                         mode: "inline",
                         validate: function (v) {
                             var reg = /^[1-9]\d*$/;
                             if (!reg.test(v)) return '请输入整数数字';
                         }
                     }*/
                }, {
                    field: 'td',
                    title: '过站休息',
                    editable: {
                        type: 'text',
                        emptytext: "请输入",
                        mode: "inline",
                        validate: function (v) {
                            var reg = /^(0|[1-9][0-9]*)$/;
                            if (!reg.test(v)) return '请输入整数数字';

                        }
                    }
                },
                /* {
                field: 'td',
                title: '计飞',
                editable: {
                    type: 'text',
                    emptytext: "请输入",
                    mode: "inline",
                    validate: function (v) {
                        var reg = /^\d{4}$/;
                        if (!reg.test(v)) return '请输入4位数字';
                        var strHour = v.substring(0, 2);
                        var hour = parseInt(strHour);
                        if (hour > 23) {
                            return '小时在0-23之间';
                        }
                        var strMin = v.substring(2, 4);
                        var min = parseInt(strMin);
                        if (min > 59) {
                            return '分钟在0-59之间';
                        }
                    },
                    display: function (value) {
                        value = value.toString().replace(/\D/g, '').replace(/..(?!$)/g, '$&:');
                        $(this).text(value);
                    }
                }
            }, {
                field: 'ta',
                title: '计达',
                editable: {
                    type: 'text',
                    emptytext: "请输入",
                    mode: "inline",
                    validate: function (v) {
                        var reg = /^\d{4}$/;
                        if (!reg.test(v)) return '请输入4位数字';
                        var strHour = v.substring(0, 2);
                        var hour = parseInt(strHour);
                        if (hour > 23) {
                            return '小时在0-23之间';
                        }
                        var strMin = v.substring(2, 4);
                        var min = parseInt(strMin);
                        if (min > 59) {
                            return '分钟在0-59之间';
                        }
                    },
                    display: function (value) {
                        value = value.toString().replace(/\D/g, '').replace(/..(?!$)/g, '$&:');
                        $(this).text(value);
                    }
                }
            },*/ {
                    field: 'operation',
                    title: '操作',
                    formatter: function (value, row, index) {
                        return '<a class="delRow ml10" href="javascript:void(0)" title="删除" onclick=delRow("'+row.id+'")>' +
                            '<span class="glyphicon glyphicon-remove text-danger"></span>' +
                            '</a>';
                    }
                }],
            onEditableSave: function (field, row, oldValue, $el) {
                if (field == "flightNoSelect") {
                    var rowFlightMap = JSON.parse(unescape($el.parent().find(".flightNo-select").data("map")));
                    row.departureAirportName = rowFlightMap.departureAirportName;
                    row.arrivalAirportName = rowFlightMap.arrivalAirportName;
                    row.departureAirport = rowFlightMap.departureAirport;
                    row.arrivalAirport = rowFlightMap.arrivalAirport;
                    row.flightNo = rowFlightMap.flightNo;
                    $("#dayTable-" + (len + 1)).bootstrapTable('updateRow', {
                        index: $el.parents("tr").data("index"),
                        row: row
                    });
                }
            }
        });

    }

    function formatState(state) {
        if (!state.id) {
            return state.text;
        }
        var $state = $(
            '<span>' + state.text + '</span>'
        );
        return $state;
    };

    function formatSelectionState(state) {
        if (!state.id) {
            return state.text;
        }
        var $state = $(
            '<span class="flightNo-select" data-map="' + escape(JSON.stringify(state.map)) + '">' + state.text + '</span>'
        );
        return $state;
    };

    function constructDayHTML(n, dayId) {
        var html = '  <div class="row item" id="day-' + n + '">' +
            '<input value="' + dayId + '" class="dayId" type="hidden"/>' +
            '                <div class="col-sm-12 col-xs-12">' +
            '                    <div class="clearfix float-e-margins table-tool">' +
            '                        <h3 class="pull-left dayText"></h3>' +
            '                        <button type="button" class="btn btn-outline btn-warning btn-add pull-right"' +
            '                                data-toggle="tooltip"\n' +
            '                                title="删除" onclick=delOneDay(this) style="margin-left:5px;">删除一天' +
            '                        </button>' +
            '                            <button type="button" class="btn btn-outline btn-success btn-add pull-right" data-toggle="tooltip"' +
            '                                    title="添加" onclick=addRow(this)>添加航段' +
            '                            </button>' +
            '                    </div>' +
            '                    <div class="clearfix float-e-margins">' +
            /*'                        <div class="pull-left"><span>过站休息(小时)：</span><input value="'+rest+'" class="restHour"/></div>' +
            '                        <div class=" table-tool pull-right">' +
            '                            <button type="button" class="btn btn-outline btn-success btn-add" data-toggle="tooltip"' +
            '                                    title="添加" onclick=addRow(this)>添加航段\n' +
            '                            </button>' +
            '                        </div>' +
            '                    </div>' +*/
            '                    <table class="table table-hover table-condensed" id="dayTable-' + n + '">' +
            '                    </table>' +
            '                </div>' +
            '            </div>';
        return html;
    }

    function updateDayText() {
        $(".item").each(function (index, ele) {
            var indexStr = "第<span class='loopDay'>" + (index + 1) + "</span>天";
            $(this).find(".dayText").html(indexStr);
            $(this).attr("id", "day-" + (index + 1));
            $(this).find(".table").attr("id", "dayTable-" + (index + 1));
        });
    }

    function delOneDay(dom) {
        var id = $(dom).parents(".item").find(".table").attr("id");
        var index = id.split("-")[1];
        $("#day-" + index).remove();
        $("#" + id).bootstrapTable('destroy');
        updateDayText();
    }

    var flightSelectData = [];

    function addRow(dom) {
        var id = $(dom).parents(".item").find(".table").attr("id");
        var len = $("#" + id).bootstrapTable('getData').length;
        var loopDay = id.split("-")[1];
        $("#" + id).bootstrapTable('insertRow', {
            index: len,
            row: {
                id: getUUID(8),
                flightNo: '',
                departureAirport: '',
                arrivalAirport: '',
                ta: '',
                td: '',
                loopDay: loopDay,
                weeks: '',
                operation: '',
                _isNew: true
            }
        });
    }

    function delRow(id){
        $("#" + $(event.target).parents("table").attr("id")).bootstrapTable('removeByUniqueId', id);
    }
    function getSource() {
        var result = [];
        $.ajax({
            url: '/pilotTaskLoop/getFlightNoList',
            async: false,
            dataType: 'json',
            data: {flightDateStart: $("#startDate").val(), flightDateEnd: $("#endDate").val()},
            success: function (data) {
                result = data;
            }
        });
        return result;
    }

    //任务环名称样式修改
    function nameFormatter(value, row, index) {
        if (value) {
            value = value.replace(/\-夜-/g, '-<img class="night" src="/img/night.png"/>-')
        }
        return value;
    }

    //权限
    function operateFormatter(value, row, index) {
        return [
            '&nbsp;&nbsp;',
            '<a class="edit ml10" href="javascript:void(0)" title="编辑">',
            '<span class="glyphicon glyphicon-edit "></span>',
            '</a>',
            '&nbsp;&nbsp;',
            '<a class="delete ml10" href="javascript:void(0)" title="删除">',
            '<span class="glyphicon glyphicon-remove text-danger"></span>',
            '</a>',
        ].join('');
    }

    //机组几人制
    function getAjaxData(reqUrl) {
        var result = [];
        $.ajax({
            url: reqUrl,
            dataType: 'json',
            cache: false,
            async: false,
            success: function (data) {
                result = data;
            },
            error: function (data) {
            }
        });
        return result;
    }

    //操作功能
    window.operateEvents = {
        //权限操作
        'click a.edit': function (e, value, row, index) {
            var id = row.id;
            layer.open({
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                area: ['900px', '80%'],
                btn: ["保存", "取消"],
                zIndex: 999,
                title: "修改任务",
                content: $("#layerBody"),
                yes: function (indexLayer, layero) {
                    var startDate = $("#startDate").val();
                    if (!startDate) {
                        toastr.warning("请选择开始日期！");
                        return;
                    }
                    var endDate = $("#endDate").val();
                    if (!endDate) {
                        toastr.warning("请选择结束日期！");
                        return;
                    }
                    var crewNumberType = $("#crewNumberType").val();
                    if (!crewNumberType) {
                        toastr.warning("请选择机组标准！");
                        return;
                    }
                    var weekFristDay = $("#weekFristDay").val();
                    if (!weekFristDay) {
                        toastr.warning("请输入始飞班期！");
                        return;
                    }
                    var params = {};
                    params.startDate = startDate;
                    params.endDate = endDate;
                    params.crewNumberType = crewNumberType;
                    params.weekFristDay = weekFristDay;
                    params.badRoute = $("#isBadRoute").val() == 0 ? false : true;
                    params.id = id;
                    var legNum = $(".item").length;
                    if (legNum == 0) {
                        if (!$("#toast-container")[0]) {
                            toastr.warning("尚未添加任务！");
                        }
                        return;
                    } else {
                        var sum = 0;
                        $("#handTable .item .table").each(function () {
                            sum += $(this).bootstrapTable("getData").length;
                        });
                        if (sum == 0) {
                            if (!$("#toast-container")[0]) {
                                toastr.warning("尚未添加航段！");
                            }
                            return;
                        }
                    }
                    params.minMale = $("#minMale").val();
                    params.internationalTimeZoneMore6 = $('#internationalTimeZoneMore6').is(":checked");
                    params.dutyCode = dutyCode;
                    params.dayList = [];
                    var isPassValid = true;
                    $("#handTable .item").each(function () {
                        var tempDayList = {};
                        tempDayList.loopDay = $(this).find(".loopDay").text();
                        tempDayList.id = $(this).find(".dayId").val();
                        var tempData = $(this).find("table").bootstrapTable("getData");
                        var isNotNull = true;
                        for (var i = 0; i < tempData.length; i++) {
                            if (!tempData[i].flightNo) {
                                toastr.warning("请输入航段的航班号");
                                isNotNull = false;
                                break;
                            }
                            if (tempData[i]._isNew) {
                                tempData[i].id = "";
                            }
                        }
                        if (isNotNull) {
                            tempDayList.flightList = tempData;
                            params.dayList.push(tempDayList);
                        } else {
                            isPassValid = false;
                        }
                    });
                    if (isPassValid) {
                        $.ajax({
                            url: url + "pilotTaskLoop/save",
                            dataType: 'json',
                            async: false,
                            type: 'post',
                            data: {data: JSON.stringify(params)},
                            success: function (data) {
                                console.log(data);
                                if (!data.errorCode && (data.success == true || data.success == "true")) {
                                    toastr.success(data.message);
                                    layer.close(indexLayer);
                                    $("#table-task").bootstrapTable("refresh");
                                }else{
                                    if (!$("#toast-container")[0]) {
                                        toastr.warning(data.message);
                                    }
                                }
                            },
                            error: function (data) {
                                if (!$("#toast-container")[0]) {
                                    toastr.warning("出错了！");
                                }
                            }
                        });
                    }
                },
                end: function (indexLayer, layero) {
                    $("#handTable").html("");
                    $("#startDate,#endDate").val(null).trigger('change');
                },
                success: function (indexLayer, indexLayer) {
                    $("#startDate").val(row.startDate).trigger("change");
                    $("#endDate").val(row.endDate).trigger("change");
                    $("#crewNumberType").val(row.crewNumberType).trigger('change');
                    $("#weekFristDay").val(row.weekFristDay);
                    $("#isBadRoute").val(row.badRoute ? 1 : 0).trigger("change");
                    $("#minMale").val(row.minMale);

                    $("#internationalTimeZoneMore6").prop("checked",row.internationalTimeZoneMore6?true:false);
                    //数据显示
                    $.ajax({
                        url: url + "pilotTaskLoop/taskLoop",
                        dataType: 'json',
                        cache: false,
                        data: {id: id},
                        success: function (data) {
                            if (data) {
                                //数据查询成功
                                for (var i = 0; i < data.dayList.length; i++) {
                                    var html = '';
                                    html = addOneDay(data.dayList[i]);
                                    $("#handTable").append(html);
                                }
                            } else {
                                toastr.error('数据查询失败，请联系信息中心！');
                            }
                        },
                        error: function (data) {
                            toastr.error('数据查询失败，请联系信息中心！');
                        }
                    });
                }
            });
        },
        'click a.delete': function (e, value, row, index) {
            layer.confirm('确认删除该任务吗?', function (index) {
                $.ajax({
                    url: url + "pilotTaskLoop/disable",
                    dataType: 'json',
                    cache: false,
                    data: {taskLoopId: row.id,dutyCode:dutyCode},
                    success: function (data) {
                        if (!data.errorCode && (data.success == true || data.success == 'true')) {
                            toastr.success('删除成功！');
                            $("#table-task").bootstrapTable("refresh");
                        } else {
                            toastr.error('数据查询失败，请联系信息中心！');
                        }
                    },
                    error: function (data) {
                        toastr.error('数据查询失败，请联系信息中心！');
                    }
                });
                layer.close(index);
            });
        }
    };

    function matchCustom(params, data) {
        // If there are no search terms, return all of the data
        if ($.trim(params.term) === '') {
            return data;
        }

        if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) >= 0 || data.id.toUpperCase().indexOf(params.term.toUpperCase()) >= 0) {
            var modifiedData = $.extend({}, data, true);
            return modifiedData;
        }
        // Return `null` if the term should not be displayed
        return data;
    }

    //状态中文化
    function routeStatusFormatter(value, row, index) {
        if (value) {
            return "<span class='glyphicon glyphicon-ok text-danger'></span>";
        } else {
            return "";
        }

    }
    function syncFData(){
        layer.open({
            type: 1,
            skin: 'layui-layer-demo', //样式类名
            area: ['600px', '400px'],
            btn: ["保存", "取消"],
            zIndex: 999,
            title: "同步飞行数据",
            content: $("#layerLinkLineDataF"),
            yes: function (indexLayer, layero) {
                var syncFLine = $("#table-linkLineF").bootstrapTable("getSelections");
                if(syncFLine.length == 0){
                    if (!$("#toast-container")[0]) {
                        toastr.warning("请选择需要同步的数据！");
                    }
                    return;
                }
                $.ajax({
                    url: url + "pilotTaskLoop/taskLoop",
                    dataType: 'json',
                    cache: false,
                    data: {id: syncFLine[0].id},
                    success: function (data) {
                        if (data) {
                            $("#handTable").html("");
                            //数据查询成功
                            for (var i = 0; i < data.dayList.length; i++) {
                                data.dayList[i].id = "";
                                for(var j=0;j<data.dayList[i].flightList.length;j++){
                                    data.dayList[i].flightList[j].id = "";
                                    data.dayList[i].flightList[j].loopId = "";
                                    data.dayList[i].flightList[j].weeks = "";
                                }
                                var html = '';
                                html = addOneDay(data.dayList[i]);
                                $("#handTable").append(html);
                            }
                            layer.close(indexLayer);
                        } else {
                            toastr.error('数据查询失败，请联系信息中心！');
                        }
                    },
                    error: function (data) {
                        toastr.error('数据查询失败，请联系信息中心！');
                    }
                });
            },
            end: function (indexLayer, layero) {
            },
            success: function (indexLayer, indexLayer) {
                $("#table-linkLineF").bootstrapTable("destroy").bootstrapTable({
                    /*数据参数清单*/
                    //分页参数
                    url: url + 'pilotTaskLoop/listTaskLoop?dutyCode=F',
                    pagination: true,//是否分页
                    pageList: [10, 25, 50, 100],
                    pageSize: 25,
                    pageNumber: 1,
                    clickToSelect: true,
                    singleSelect: false,
                    showRefresh: false,                  //是否显示刷新按钮
                    uniqueId: 'id',
                    striped: true,//行间隔色
                    locale: "${language}",
                    onClickRow: function (row, $element) {
                        $element.addClass('info').siblings().removeClass('info').end();
                    }
                });
            }
        });

    }
</script>
</body>
</html>